"""
Author        yongfa
Date          2022-07-18 15:01:16
LastEditTime  2022-10-14 15:32:42
LastEditors   yongfa
Description   业务逻辑
"""

from flask_restx import Resource

from flask import send_file
from app.extensions.decorators import casbin_required
from .parameters import get_list_params, create_params, delete_params
from .models import Files
from .services import UploaderService


def configure_router(ns):

    @ns.route('')
    class UploadResource(Resource):
        method_decorators = [casbin_required]

        @ns.doc(parser=create_params)
        def post(self):
            """上传文件"""
            return UploaderService(model=Files, args=create_params).upload()

        @ns.doc(parser=delete_params)
        def delete(self):
            """删除文件"""
            return UploaderService(model=Files, args=delete_params).delete()

        @ns.doc(parser=get_list_params)
        def get(self):
            """获取文件列表"""
            return UploaderService(model=Files, args=get_list_params).get_list()

    @ns.route('/<int:id>')
    @ns.doc(params={"id": "文件ID"})
    class UploadDetailResource(Resource):
        method_decorators = [casbin_required]

        def get(self, id):
            """获取文件详情"""
            return UploaderService(model=Files, args=get_list_params).get_detail(id)

    @ns.route('/detail/<string:filename>')
    class UploadAccessResource(Resource):
        def get(self, filename):
            import base64
            import time
            from app.extensions.utils.encryption import Prpcrypt
            from app.extensions.exception import Failed
            aes = Prpcrypt(key='ao0oiou9S6na35Uvxa09SQ==')
            timestamp = int(time.time())  # 秒

            file = '/default/2022-10-14-13/7efa0df497954ab2ab52541e026d36f8.png'

            file_str = file + '&' + str(timestamp + 10)
            secret_data = aes.encrypt(file_str)
            print(base64.b64encode(secret_data.encode('utf8')))

            filename_str = base64.b64decode(filename).decode('utf-8')
            aes_str = aes.decrypt(filename_str)
            aes_str_list = aes_str.split('&')
            file_str = aes_str_list[0]
            file_timestamp = aes_str_list[1]
            # if timestamp > int(file_timestamp):
            #     return Failed(message='文件已过期')

            # str_filename = base64.b64decode(filename).decode('utf-8')
            str_filename = 'app/static/uploads' + file_str
            return send_file('{}'.format(str_filename))
